#include "Socket.h"

int conectSocket(int* sock, const char* host, int puerto) {

	struct sockaddr_in serv_addr;
	struct hostent *server;

	*sock = socket(AF_INET, SOCK_STREAM, 0);
	if (socket < 0) return ERROR;
	
	server = gethostbyname(host);
	if (server == NULL) return ERROR;

	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
	serv_addr.sin_port = htons(puerto);

	if (connect(*sock,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) return ERROR;

	return OK;
}

int disconectSocket(int socket) {
	close(socket);
	return 0;
}

int readSocket(int socket, string* datos, int bytes) {
	
	if (bytes == 0) return OK;
	
	char buffer[bytes+1];
	bzero(buffer, bytes);
	int leidos = 0;
	int res;

	while (leidos < bytes) 
	{
		res = recv(socket, buffer+leidos, bytes-leidos, 0);
				
		if (res < 0) {
			if ( errno == EAGAIN || errno == EWOULDBLOCK) return SIN_CONEXION;
			else return ERROR;
		}
		if (res == 0) return SIN_CONEXION;
		
		leidos += res;
	}
	
	buffer[leidos] = '\0';	
	*datos = string(buffer);

	return OK;
	
}

int writeSocket(int socket, string mensaje) {
	
	int escritos = 0;
	int res;
	
	while (escritos < (int)mensaje.size()) {

		res = send(socket, mensaje.c_str()+escritos, mensaje.size()-escritos, MSG_NOSIGNAL);
		
		if (res < 0) {
			if (errno == EPIPE) return SIN_CONEXION;
			if (errno == EAGAIN || errno == EWOULDBLOCK) return SIN_CONEXION;
			else return ERROR;
		}
		
		escritos += res;
	}
	
	return OK;
}
